<script setup>
	import {
		ref,
		onMounted,
		onUnmounted,
		provide,
		watch
	} from 'vue'
	import {
		ENGINE_LEFT,
		ENGINE_RIGHT
	} from '@/utils/const.js'
	let ws = ref(null)
	let allData = ref({
		communication: true
	})
	let engine = ref(ENGINE_LEFT)
	let url = ref(localStorage.getItem('url') || "ws://47.119.186.103:9998/websocket");
	let name = ref(localStorage.getItem('name') || '中舟一号')
	let bucketName = ref(localStorage.getItem('bucketName') || 'ship_one')
	provide('engine', engine)
	provide('allData', allData)
	provide('url', url)
	provide('name', name)
	provide('bucketName', bucketName)

	const WSClient = () => {
		let localUrl = localStorage.getItem('url')
		if (!localUrl) {
			localUrl = url.value
			localStorage.setItem('url', url.value)
			localStorage.setItem('name', name.value)
			localStorage.setItem('bucketName', bucketName.value)
		}
		ws.value = new WebSocket(localUrl)
		ws.value.onopen = (e) => {
			console.log('open', e)
		}
		ws.value.addEventListener('message', function(event) {
			let {
				state,
				gpsPostitionDeviceService,
				shiplogDeviceService
			} = JSON.parse(event.data) || {}
			Object.assign(allData.value, JSON.parse(event.data) || {})
			allData.value.geo = gpsPostitionDeviceService
			allData.value.apparatus = shiplogDeviceService
			allData.value.communication = !state
			console.log(allData.value, 'allData====>')
		})
		ws.value.onerror = (e) => {
			allData.value.communication = true
			WSClient()
		}
		ws.value.onclose = () => {
			allData.value.communication = true
		}
	}

	// 初始化 WebSocket 连接
	WSClient()

	watch(
		() => url.value,
		(newVal, oldVal) => {
			ws.value.close()
			WSClient()
		}
	)
</script>

<style lang="scss">
	@import "@/uni_modules/uview-plus/index.scss";
	/*每个页面公共css */
	@import '@/uni_modules/uni-scss/index.scss';
	/* #ifndef APP-NVUE */
	@import '@/static/customicons.css';

	// 设置整个项目的背景色
	page {
		display: initial !important;
		box-sizing: border-box;
		width: 100%;
		/* 可添加其他自定义样式，如修改背景颜色 */
		background-color: #f5f5f5;
	}

	/* #endif */
	.example-info {
		font-size: 14px;
		color: #333;
		padding: 10px;
	}
</style>